﻿using System;
using SoldiHive.Infrustructure.Extensions;
using System.Collections.Generic;

namespace SoldiHive.Model
{
	[Serializable]
	public class EarningsStatement : IFormattable
	{
		public DateTime Date { get; set; }
		public Time Time { get; set; }
		public Company Company { get; set; }

		public DateTime LocalStatementDateTime 
		{
			get
			{
				const int stockShiftHours = 5;

				var localShiftHours = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours;

				var hour = 0;
				var minute = 0;
				if (this.Time == Time.Before)
				{
					hour = 9;
					minute = 30;
				}
				else if (this.Time == Time.After)
				{
					hour = 16;
				}

				var localStatementDateTime = new DateTime(this.Date.Year, this.Date.Month, this.Date.Day, hour, minute, 0);
				localStatementDateTime = localStatementDateTime.AddHours(stockShiftHours);
				localStatementDateTime = localStatementDateTime.AddHours(localShiftHours);

				return localStatementDateTime;
			}
		}

		public EarningsStatement()
		{
			this.Date = new DateTime();
			this.Time = Time.NA;
			this.Company = null;
		}

		public override bool Equals(object obj)
		{
			if (!(obj is EarningsStatement) || obj == null)
			{
				return false;
			}

			var earningsStatement = obj as EarningsStatement;

			return string.Equals(this.Date, earningsStatement.Date) &&
				string.Equals(this.Time, earningsStatement.Time) &&
				string.Equals(this.Company, earningsStatement.Company);
		}

		public override int GetHashCode()
		{
			return base.GetHashCode();
		}

		public static bool operator ==(EarningsStatement left, EarningsStatement right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(EarningsStatement left, EarningsStatement right)
		{
			return !(left == right);
		}

		public override string ToString()
		{
			var statement = string.Format("{0}", this);

			return statement;
		}

		public string ToString(string format, IFormatProvider formatProvider)
		{
			if (string.IsNullOrEmpty(format))
			{
				format = "Date,Time,Company";
			}

			var propertyNames = format.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

			var values = new List<string>();
			foreach (var propertyName in propertyNames)
			{
				var value = string.Empty;

				if (propertyName.Equals("Date", StringComparison.InvariantCultureIgnoreCase))
				{
					value = string.Format("{0:dd MMM yyy (ddd)}", this.Date);
				}
				else if (propertyName.Equals("Time", StringComparison.InvariantCultureIgnoreCase))
				{
					value = string.Format("[{0}]", this.Time);
					value = value.Align(" ", 8);
				}
				else
				{
					value = this.Company.ToString();
				}

				values.Add(value);
			}

			var statementString = string.Join(" ", values);

			return statementString;
		}
	}
}
